package com.zmn.mcc.admin.controller.staff;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.request.RequestUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.manager.redis.lock.DistributedLock;
import com.zmn.manager.redis.lock.DistributedLockUtils;
import com.zmn.mcc.common.constant.StaffConsts;
import com.zmn.mcc.model.entity.dept.McDept;
import com.zmn.mcc.model.entity.staff.McStaff;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author heguanghua
 * @since 2020/04/15 10:54
 */
@Controller
@RequestMapping("/staff/modify/")
public class StaffModifyController extends StaffBaseController {

    private Logger logger = LoggerFactory.getLogger(StaffModifyController.class);

    private static final String LOCK_SYNC_DATA = "lock:sync:data:";

    @Value("${spring.mq.topic.mcc}")
    public String mccTopic;

    @NacosValue(value = "${mcc.staff.tmp.pwd.loginUrl}", autoRefreshed = true)
    private String tmpPwdLogin;

    @Resource
    ZmnMQSender zmnMQSender;

    /**
     * 新增/修改
     */
    @RequestMapping("addEdit")
    @ResponseBody
    public ResponseDTO addEdit(HttpServletRequest request, HttpServletResponse response,
                               @RequestBody McStaff staff) {

        staff.setStaffNumber(staff.getStaffName());
        staff.setUpdater(getStaffName());
        // 设置所有上级部门
        List<McDept> mcDepts = deptBService.listDeptForAbove(staff.getDeptId(), true);
        for (McDept mcDept : mcDepts) {
            if (Objects.isNull(mcDept) || Objects.isNull(mcDept.getLevel())) {
                continue;
            }
            switch (mcDept.getLevel()) {
                case GlobalConsts.LEVEL_1:
                    staff.setDeptOneId(mcDept.getDeptId());
                    break;
                case GlobalConsts.LEVEL_2:
                    staff.setDeptTwoId(mcDept.getDeptId());
                    break;
                case GlobalConsts.LEVEL_3:
                    staff.setDeptThrId(mcDept.getDeptId());
                    break;
                case GlobalConsts.LEVEL_4:
                    staff.setDeptFourId(mcDept.getDeptId());
                    break;
                case GlobalConsts.LEVEL_5:
                    staff.setDeptFiveId(mcDept.getDeptId());
                    break;
            }
        }

        // 设置直线经理
        McStaff leader = staffService.findByKey(staff.getLeaderId());
        if (Objects.isNull(leader)) {
            return ResponseDTO.fail("直线经理不存在");
        }
        staff.setLeaderName(leader.getRealName());

        String ip = RequestUtil.getRequestIp(request);
        if (NumberUtil.isNullOrZero(staff.getStaffId())) {
            return staffBService.addStaff(staff, getLoginStaff(), ip);
        } else {
            return staffBService.modifyStaff(staff, getLoginStaff(), ip);
        }
    }

    /**
     * 修改可用状态
     */
    @RequestMapping("modifyStatus")
    @ResponseBody
    public ResponseDTO modifyStatus(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "ids", defaultValue = "") String ids,
                                    @RequestParam(value = "status", defaultValue = "0") Integer status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的员工");
        }
        String ip = RequestUtil.getRequestIp(request);
        List<Integer> arrayIds = StringUtil.convertStrsToList(ids);
        staffService.updateStatusBatch(arrayIds, status, getLoginStaff(), ip);
        return ResponseDTO.success(null, "操作成功");
    }

    /**
     * 修改排序值
     */
    @RequestMapping("modifySort")
    @ResponseBody
    public ResponseDTO modifySort(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id", defaultValue = "0") Integer id,
                                  @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (NumberUtil.isNullOrZero(id)) {
            return ResponseDTO.fail("请选择要更改排序的员工");
        }
        if (NumberUtil.isNullOrZero(sort)) {
            return ResponseDTO.fail("请设置员工排序值");
        }

        staffService.updateSort(id, sort);
        return ResponseDTO.success(null, "操作成功");
    }

    /**
     * 设置临时密码
     */
    @RequestMapping("setTempPwd")
    @ResponseBody
    public ResponseDTO setTempPwd(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                                  @RequestParam(value = "password", defaultValue = "") String password) {

        String ip = RequestUtil.getRequestIp(request);
        return staffBService.setTempPwd(staffId, password, getLoginStaff(), ip, tmpPwdLogin);
    }

    /**
     * 重设密码
     */
    @RequestMapping(value = "resetPwd")
    @ResponseBody
    public ResponseDTO resetPwd(HttpServletRequest request, @RequestParam(value = "id", defaultValue = "") String staffIds) {

        if (StringUtils.isEmpty(staffIds)) {
            return ResponseDTO.fail("请选择要重置密码的员工！");
        }

        String ip = RequestUtil.getRequestIp(request);
        String pwd = staffBService.resetPwd(staffIds, getLoginStaff(), ip);

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, new StringBuilder("重置密码成功，默认密码：").append(pwd).toString());
    }

    /**
     * 设置不限IP日期
     */
    @RequestMapping("setOpenDate")
    @ResponseBody
    public ResponseDTO setOpenDate(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                                   @RequestParam(value = "dateRange", defaultValue = "") String dateRange) {

        String ip = RequestUtil.getRequestIp(request);
        return staffBService.setOpenDate(staffId, dateRange, getLoginStaff(), ip);
    }

    @RequestMapping("batch/opendate")
    @ResponseBody
    public ResponseDTO<String> batchOpendate(HttpServletRequest request,
                                             @RequestParam(value = "ids", defaultValue = "") String ids,
                                             @RequestParam(value = "dateRange", defaultValue = "") String dateRange) {
        String ip = RequestUtil.getRequestIp(request);
        return staffBService.batchSetOpenDate(StringUtil.convertStrsToList(ids), dateRange, getLoginStaff(), ip);
    }

    /**
     * 设置IP白名单
     */
    @RequestMapping("setWhitelist")
    @ResponseBody
    public ResponseDTO setWhitelist(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                                    @RequestParam(value = "whitelist", defaultValue = "1") Integer whitelist) {

        String ip = RequestUtil.getRequestIp(request);
        return staffBService.setWhitelist(staffId, whitelist, getLoginStaff(), ip);
    }

    /**
     * 绑定工程师
     */
    @RequestMapping("bindMaster")
    @ResponseBody
    public ResponseDTO bindMaster(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                                  @RequestParam(value = "masterIds", defaultValue = "") String masterIds) {

        String ip = RequestUtil.getRequestIp(request);
        return staffBService.bindMaster(staffId, StringUtil.split(masterIds, Integer.class), getStaffName(), ip);
    }

    /**
     * 同步人事系统
     */
    @RequestMapping("syncBeisengData")
    @ResponseBody
    public ResponseDTO syncBeisengData(HttpServletRequest request, HttpServletResponse response) {

        // 加锁，限制5分钟内最多同步一次
        String redisLockKey = LOCK_SYNC_DATA + getStaffId();
        DistributedLock redisLock = DistributedLockUtils.build(redisLockKey, 300);
        if (redisLock.tryLock()) {
            String uuid = UUID.randomUUID().toString();
            try {
                logger.info("同步人事系统发送mq消息,uuid:{}", uuid);
                zmnMQSender.send(mccTopic, StaffConsts.SYNC_BERSENGDATA_TAG, uuid, "true");
                return ResponseDTO.success();
            } catch (Exception e) {
                logger.error("同步人事系统发送mq消息异常，msg:{}", e.getMessage());
                redisLock.unlock();
                throw new RuntimeException("同步人事系统发送mq消息异常");
            }
        } else {
            logger.error("尝试获取锁失败，不能同步数据");
            return ResponseDTO.fail("正在同步数据，请稍后再试！");
        }


    }

//    /**
//     * 描述: 重建员工es索引
//     *
//     * @return com.zmn.oms.common.dto.ResultDTO
//     * @author wangjie
//     * @since 10:28 2019/4/18
//     **/
//    @RequestMapping(value = "rebuildStaffIndex")
//    @ResponseBody
//    public ResponseDTO rebuildStaffIndex() {
//        try {
//            esStaffService.initEsData();
//        } catch (Exception e) {
//            logger.error("重建员工索引失败", e);
//            return ResponseDTO.fail("重建员工索引失败");
//        }
//
//        return ResponseDTO.fail("重建员工索引成功");
//    }
}
